#!/usr/bin/env node

import fs from 'fs'
import path from 'path'
import { fileURLToPath } from 'url'

const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)
const projectRoot = path.resolve(__dirname, '..')

console.log('🔍 验证Chrome扩展构建结果...\n')

const checks = []

// 检查函数
function addCheck(name, condition, message) {
  checks.push({
    name,
    passed: condition,
    message: message || ''
  })
}

// 1. 检查基础文件结构
const distDir = path.join(projectRoot, 'dist')
const unpackedDir = path.join(distDir, 'unpacked')
const zipPath = path.join(distDir, 'ChromeExt.zip')

addCheck('dist目录存在', fs.existsSync(distDir))
addCheck('unpacked目录存在', fs.existsSync(unpackedDir))
addCheck('ChromeExt.zip文件存在', fs.existsSync(zipPath))

// 2. 检查关键文件
const manifestPath = path.join(unpackedDir, 'manifest.json')
const serviceWorkerPath = path.join(unpackedDir, 'serviceWorker.js')
const sidepanelPath = path.join(unpackedDir, 'src/sidepanel/sidepanel.html')

addCheck('manifest.json存在', fs.existsSync(manifestPath))
addCheck('serviceWorker.js存在', fs.existsSync(serviceWorkerPath))
addCheck('sidepanel.html存在', fs.existsSync(sidepanelPath))

// 3. 检查图标文件
const iconSizes = [16, 32, 48, 128]
for (const size of iconSizes) {
  const iconPath = path.join(unpackedDir, `icons/icon${size}.png`)
  addCheck(`icon${size}.png存在`, fs.existsSync(iconPath))
}

// 4. 检查manifest.json内容
if (fs.existsSync(manifestPath)) {
  try {
    const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'))

    addCheck('manifest版本正确', manifest.manifest_version === 3)
    addCheck('扩展名称正确', manifest.name === 'SideX')
    addCheck('权限配置正确', Array.isArray(manifest.permissions) && manifest.permissions.includes('sidePanel'))
    addCheck('侧边栏配置正确', manifest.side_panel && manifest.side_panel.default_path)
    addCheck('背景脚本配置正确', manifest.background && manifest.background.service_worker)
    addCheck('内容脚本配置正确', Array.isArray(manifest.content_scripts) && manifest.content_scripts.length > 0)
  } catch (error) {
    addCheck('manifest.json格式正确', false, error.message)
  }
}

// 5. 检查CSS和JS文件
const cssFiles = fs.readdirSync(path.join(unpackedDir, 'assets')).filter(f => f.endsWith('.css'))
const jsFiles = fs.readdirSync(path.join(unpackedDir, 'assets')).filter(f => f.endsWith('.js'))

addCheck('CSS文件存在', cssFiles.length > 0, `找到 ${cssFiles.length} 个CSS文件`)
addCheck('JS文件存在', jsFiles.length > 0, `找到 ${jsFiles.length} 个JS文件`)

// 6. 检查ZIP文件大小
if (fs.existsSync(zipPath)) {
  const stats = fs.statSync(zipPath)
  const sizeInMB = (stats.size / 1024 / 1024).toFixed(2)
  const isValidSize = stats.size < 128 * 1024 * 1024 // 128MB限制

  addCheck('ZIP文件大小合理', isValidSize, `大小: ${sizeInMB} MB`)
}

// 7. 检查工具栏相关文件
const toolbarComponentExists = fs.existsSync(path.join(projectRoot, 'src/sidepanel/components/layout/Toolbar.vue'))
addCheck('工具栏组件存在', toolbarComponentExists)

// 输出结果
console.log('📋 验证结果:\n')

let passed = 0
let total = checks.length

checks.forEach(check => {
  const status = check.passed ? '✅' : '❌'
  const message = check.message ? ` (${check.message})` : ''
  console.log(`${status} ${check.name}${message}`)

  if (check.passed) passed++
})

console.log(`\n📊 验证总结: ${passed}/${total} 项检查通过`)

if (passed === total) {
  console.log('\n🎉 所有检查都通过！构建结果符合Phase 0要求')
  console.log('\n📝 可以进行以下操作:')
  console.log('1. 在Chrome中加载 dist/unpacked 目录测试扩展')
  console.log('2. 将 dist/ChromeExt.zip 上传到Chrome Web Store')

  process.exit(0)
} else {
  console.log('\n⚠️  发现问题，请检查失败的项目')
  process.exit(1)
}